from django.db import models
from DjangoUeditor.models import UEditorField
from django.contrib.auth.models import User
import os
from single_blog import settings
from Utils.PngUtils import make_thumb
from django.db.models.fields.files import ImageFieldFile


# Create your models here.
class Sentence(models.Model):
    '''每日一句表'''
    content = models.TextField()
    time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.content

    class Meta:
        verbose_name_plural = "每日一句"


class Tag(models.Model):
    '''标签表'''
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "标签表"


class Post(models.Model):
    """文章"""
    title = models.CharField("标题", max_length=50)
    # content = models.TextField("内容")
    content = UEditorField("内容", width=800, height=500, imagePath='myblog')
    img = models.ImageField()  # 图片
    pub_time = models.DateTimeField("创建时间", auto_now_add=True)
    modify_time = models.DateTimeField("修改时间", auto_now=True)
    source = models.CharField("来源", max_length=100)
    choices = (
        ("网站前端", "网站前端"),
        ("后端技术", "后端技术"),
    )
    classify = models.CharField("分类", max_length=20, choices=choices)  # choices用来限制可选择的
    look = models.IntegerField("围观次数", default=0)
    zan = models.IntegerField("点赞", default=0)
    adv = models.BooleanField("广告位", default=False)  # 是否在轮播图投放

    # 作者
    author = models.ForeignKey(User)
    # 标签
    tags = models.ManyToManyField(Tag)
    # 略缩图
    thumb = models.ImageField(upload_to='thumb/')


    def author_(self):
        return self.author

    author_.short_description = "作者"

    def tag(self):
        return "//".join([tag.name for tag in self.tags.all()])

    tag.short_description = "标签"

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = "文章表"

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 调用父类将上传的数据进行保存
        super(Post, self).save()
        # 自动生成略缩图
        # 1.获取压缩图名称和后缀
        img_name, ext = os.path.splitext(os.path.basename(self.img.path))
        # 2.获取是上传大图的路径
        img_path = self.img.path
        # 3.提取压缩图
        pix = make_thumb(img_path)
        # 4.获取压缩图保存路径
        thumb_path = os.path.join(settings.THUMB_DIR, f'{img_name}_thumb{ext}')
        # 5.保存
        pix.save(thumb_path)
        # 6.图片url保存到数据库中
        thumb_url = thumb_path.split(settings.BASE_DIR)[-1]
        self.thumb = ImageFieldFile(self, self.thumb, thumb_url)
        # 再次保存你
        super(Post, self).save()



class Comment(models.Model):
    '''评论表'''
    name = models.CharField(max_length=20)
    email = models.CharField(max_length=20)
    content = models.TextField()
    time = models.DateTimeField(auto_now=True)
    post = models.ForeignKey(Post)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "评论表"
